#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstdio>

#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)

#define PATH "."
#define Name "fifo"

// 构建命名管道类

class NamedFifo
{
public:
    NamedFifo(const std::string &path, const std::string &name)
        : _path(path), _name(name)
    {
        umask(0);
        _fifoname = _path + _name;
        // 建立管道文件
        int n = mkfifo(_fifoname.c_str(), 0666);
        if (n == 0)
        {
            // success
            std::cout << "mkfifo success" << std::endl;
        }
        else
        {
            // fail
            ERR_EXIT("mkfifo");
        }
    }

    void OpenForWrite()
    {
        _fd = open(_fifoname.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            // fail
            ERR_EXIT("open");
        }
        std::cout << "open success" << std::endl;
    }
    void OpenForRead()
    {
        _fd = open(_fifoname.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            // fail
            ERR_EXIT("open");
        }
        std::cout << "open success" << std::endl;
    }
    void Write()
    {
        std::string message;

        while (true)
        {
            std::cout << "please Enter#" << std::endl;
            std::getline(std::cin, message);
            int n = write(_fd, message.c_str(), message.size());
            if (n < 0)
            {
                ERR_EXIT("write");
            }
        }
    }
    void Read()
    {
        while (true)
        {
            char buffer[1024];
            int n = read(_fd, buffer, sizeof(buffer) - 1); // 为啥要-1呢？？
            if (n < 0)
            {
                std::cout << "read err!" << std::endl;
                break; 
            }
            else if (n == 0)
            {
                std::cout << "client quit! me too" << std::endl;
                break;
            }
            else
            {
                // success
                std::cout << "Client say#" << buffer << std::endl;
            }
        }
    }

    void Close()
    {
        if(_fd > 0)
            close(_fd);
    }

    ~NamedFifo()
    {
        // 删除管道文件
        int n = unlink(_fifoname.c_str());
        if (n < 0)
        {
            // fail
            ERR_EXIT("unlink");
        }
        else
        {
            // success
            std::cout << "delete success" << std::endl;
        }
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
    int _fd;
};

